package account

import (
	"context"
	"encoding/json"
	"pusher/internal/svc"
	"pusher/internal/types"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 用户登录
func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	l.Logger.Info("LoginLogic Login: %#v", req)
	//记录日志
	go func() {
		logData := map[string]any{
			"username": req.Username,
			"ip":       l.ctx.Value("ip"),
			"time":     time.Now().Format("2006-01-02 15:04:05"),
			"type":     "login",
			"msg":      "登录",
		}
		bytes, _ := json.Marshal(logData)
		err = l.svcCtx.KafkaPushCli.PushWithKey(context.Background(), "log_20241031", string(bytes))
		if err != nil {
			l.Logger.Error("kafka push error: %#v", err)
		}
	}()
	return &types.LoginResp{
		Token: "token 123",
	}, nil
}
